<template>
  <div class="order-refund">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="退款状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 退款列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span>退款列表</span>
            <el-tag type="info" class="total-tag">共 {{ page.total }} 条记录</el-tag>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="handleExport">导出记录</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="refundList"
        border
        style="width: 100%"
      >
        <el-table-column prop="orderNo" label="订单编号" min-width="180" show-overflow-tooltip />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="serviceName" label="服务项目" min-width="150" show-overflow-tooltip />
        <el-table-column prop="amount" label="退款金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="退款原因" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getRefundStatusTag(row.status)">
              {{ getRefundStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" min-width="180" />
        <el-table-column prop="processTime" label="处理时间" min-width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="success" 
              link 
              @click="handleProcess(row)"
            >
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 退款详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="退款详情"
      width="600px"
    >
      <div class="refund-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ currentRefund.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="退款状态">
            <el-tag :type="getRefundStatusTag(currentRefund.status)">
              {{ getRefundStatusLabel(currentRefund.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ currentRefund.customerName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentRefund.customerPhone }}</el-descriptions-item>
          <el-descriptions-item label="服务项目">{{ currentRefund.serviceName }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ currentRefund.orderAmount?.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="退款金额">¥{{ currentRefund.amount?.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="退款原因">{{ currentRefund.reason }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ currentRefund.createTime }}</el-descriptions-item>
          <el-descriptions-item label="处理时间">{{ currentRefund.processTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="处理备注" :span="2">{{ currentRefund.processRemark || '-' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 处理记录 -->
        <div class="process-records" v-if="currentRefund.processRecords?.length">
          <h3>处理记录</h3>
          <el-timeline>
            <el-timeline-item
              v-for="record in currentRefund.processRecords"
              :key="record.id"
              :type="getTimelineItemType(record.status)"
              :timestamp="record.createTime"
            >
              <h4>{{ record.operator }}</h4>
              <p>处理结果：{{ getRefundStatusLabel(record.status) }}</p>
              <p>处理说明：{{ record.remark }}</p>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>

    <!-- 退款处理对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="退款处理"
      width="500px"
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理结果" prop="status">
          <el-radio-group v-model="processForm.status">
            <el-radio label="approved">通过</el-radio>
            <el-radio label="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理说明" prop="remark">
          <el-input
            v-model="processForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入处理说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleProcessSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getMerchantOrderRefundList,
  getMerchantOrderRefundDetail,
  processMerchantOrderRefund,
  exportMerchantOrderRefunds
} from '@/api/merchant'

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  status: '',
  dateRange: []
})

// 分页信息
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 退款列表数据
const loading = ref(false)
const refundList = ref([])

// 退款详情对话框
const detailDialogVisible = ref(false)
const currentRefund = ref({})

// 退款处理对话框
const processDialogVisible = ref(false)
const processFormRef = ref(null)
const processForm = reactive({
  id: '',
  status: 'approved',
  remark: ''
})

// 处理表单验证规则
const processRules = {
  status: [
    { required: true, message: '请选择处理结果', trigger: 'change' }
  ],
  remark: [
    { required: true, message: '请输入处理说明', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 获取退款列表
const getRefundList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1],
      page: page.current,
      size: page.size
    }
    const { data } = await getMerchantOrderRefundList(params)
    refundList.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取退款列表失败:', error)
    ElMessage.error('获取退款列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getRefundList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 查看退款详情
const handleView = async (row) => {
  try {
    const { data } = await getMerchantOrderRefundDetail(row.id)
    currentRefund.value = data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取退款详情失败:', error)
  }
}

// 处理退款
const handleProcess = (row) => {
  currentRefund.value = row
  processForm.id = row.id
  processForm.status = 'approved'
  processForm.remark = ''
  processDialogVisible.value = true
}

// 提交处理
const handleProcessSubmit = async () => {
  if (!processFormRef.value) return
  
  try {
    await processFormRef.value.validate()
    await processMerchantOrderRefund(processForm)
    ElMessage.success('处理成功')
    processDialogVisible.value = false
    getRefundList()
  } catch (error) {
    console.error('处理退款失败:', error)
  }
}

// 导出退款记录
const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    await exportMerchantOrderRefunds(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出退款记录失败:', error)
  }
}

// 获取退款状态标签类型
const getRefundStatusTag = (status) => {
  const statusMap = {
    pending: 'warning',
    processing: 'primary',
    approved: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || ''
}

// 获取退款状态标签文本
const getRefundStatusLabel = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

// 获取时间线项目类型
const getTimelineItemType = (status) => {
  const typeMap = {
    pending: 'warning',
    processing: 'primary',
    approved: 'success',
    rejected: 'danger'
  }
  return typeMap[status] || ''
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getRefundList()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getRefundList()
}

onMounted(() => {
  getRefundList()
})
</script>

<style lang="scss" scoped>
.order-refund {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        display: flex;
        align-items: center;
        gap: 10px;

        .total-tag {
          font-size: 13px;
        }
      }
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .refund-detail {
    .process-records {
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #eee;

      h3 {
        margin-bottom: 20px;
        font-size: 16px;
        font-weight: 500;
      }

      h4 {
        margin: 0 0 10px;
        font-size: 14px;
        font-weight: 500;
      }

      p {
        margin: 5px 0;
        font-size: 13px;
        color: #666;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 